/**
 * @file
 * @auth zhaojing
 * @date 2016/11/21
 */

import Vue from 'vue';
import Pager from '../../../../grsc-base/component/Pager.vue';
import Loading from '../../../../grsc-base/component/Loading.vue';
import NoData from '../../../../grsc-base/component/NoData.vue';
import Tooltip from '../../../../grsc-base/component/Tooltip.vue';
import filter from '../../../../grsc-base/util/filter';
import {PAGE_SIZE} from '../../../../grsc-base/common/constants';
import tpl from './tpl.html';
// import service from './service';
import commonService from '../../../common/commonService';
import symbolConfig from '../../../common/symbolConfig';
import format from '../../../common/format';
import service from './service';
import CONFIG from './config';
import MathTool from '../../../../grsc-base/util/mathtool';

import Deposit from './deposit/main';
import Withdraw from './withdraw/main';
import ForkInfo from '../component/ForkInfo.vue'
import setPayPwd from '../../../component/setPayPwd/main';
import sorttool from '../../../../grsc-base/util/sorttool';

const DO_TYPE_DEPOSIT = 'DEPOSIT';
const DO_TYPE_WITHDRAW = 'WITHDRAW';

export default Vue.extend({
    name: 'Asset',
    template: tpl,
    components: {
        Pager,
        Loading,
        NoData,
        Deposit,
        Withdraw,
        ForkInfo,
        setPayPwd,
        Tooltip
    },
    data() {

        return {
            coinType: '',
            doType: DO_TYPE_DEPOSIT,
            tabType: 'digital',

            list: null,
            isLoading: false,
            CONFIG: CONFIG,
            filter: filter,
            condition: {
                pageNo: 1,
                pageSize: PAGE_SIZE
            },
            pageNum: 0,

            assets: {},
            showForkInfo: false,
            forkInfoCoin: '',

            totalBTC: '--',
            totalValue: '--',   //总资产
            btcPrice: 0,
            isSetPayPassword: false,
            isShowSetPayPwd: false,
            forkType: '',
            keyCoin: '',
            hide0Balance:false //true 隐藏为0的资产
        }
    },
    computed: {},
    created() {
        this.getTotalAssets();
        this.fetchPayPsdStatus();
    },

    methods: {


        formatMoney(money, type) {
            if ($.isNumeric(money) === false) {
                return money;
            }
            money = format.formatZeroSuffix(filter.floorFixPrice(money, 8), 8);
            let index = money.indexOf('.');
            let prefix = money.substring(0, index);
            let suffix = money.substring(index + 1);
            if (type === 'GRAY') {
                return '<span class="em">' + prefix + '.</span><em class="em">' + suffix + '</em>';
            }
            return '<span class="strong">' + prefix + '.</span><em class="em">' + suffix + '</em>';
        },

        getCoinDepositWithdrawList() {
            $.when(service.depositAssetList(), service.withdrawAssetList()).done((depositRep, withdrawRep) => {
                this._doCoinList(depositRep.data, withdrawRep.data)
            });
        },

        _doCoinList(depositList, withdrawList) {
            if (depositList) {
                $.map(depositList, (item) => {
                    if (this.assets[item]) {
                        this.assets[item].deposit = true;
                    }
                });
            }

            if (withdrawList) {
                $.map(withdrawList, (item) => {
                    if (this.assets[item]) {
                        this.assets[item].withdraw = true;
                    }
                });
            }
        },

        getTotalAssets() {
            this.isLoading = true;
            $.when(commonService.getBitfinexBtcPrice(), commonService.getTradeDetail(), commonService.getTotalAssets()).done((btcPriceRep, detailRep, assetRep) => {
                this.isLoading = false;

                if (btcPriceRep.code === window.CODE.SUCCESS) {
                    this.btcPrice = btcPriceRep.data.last_price;
                } else {
                    window.error(btcPriceRep.msg);
                }

                if (assetRep.code === window.CODE.SUCCESS) {
                    this._doAssetData(assetRep.data);
                    this._doCurrentPrice(detailRep);
                    this._getTotalValue();
                } else {
                    window.error(assetRep.msg);
                }
            });
        },


        _doCurrentPrice(data) {
            let that = this;
            $.map(that.assets, (item) => {
                let price = caculateBtcPrice(item, data);

                if (that.assets[item.assetCode]) {
                    that.assets[item.assetCode].price = price;
                }
            });


            function caculateBtcPrice(item, tradeDetailMap) {
                let price = 0;

                if (item.assetCode === 'BTC') {    // BTC
                    price = 1;
                    return price;
                }

                if (item.assetCode === 'USDT' || item.assetCode === 'USC') {
                    let tradeObj = tradeDetailMap[item.assetCode + '_BTC'];
                    if (tradeObj && tradeObj.newPrice) {
                        price = MathTool.division(1, tradeObj.newPrice);
                    } else {
                        price = 0;
                    }
                    return price;
                }

                // 如 ACT/BTC
                if (tradeDetailMap['BTC_' + item.assetCode]) {
                    if (tradeDetailMap['BTC_' + item.assetCode]['newPrice']) {
                        price = tradeDetailMap['BTC_' + item.assetCode]['newPrice'];
                    } else {
                        price = 0;
                    }
                    return price;
                }

                // 如 ACT/USDT
                if (tradeDetailMap['USDT_' + item.assetCode]) {
                    if (tradeDetailMap['USDT_' + item.assetCode]['newPrice']) {
                        price = tradeDetailMap['USDT_' + item.assetCode]['newPrice'];
                    } else {
                        price = 0;
                    }
                    return price;
                }

                // 如 ACT/USC
                if (tradeDetailMap['USC_' + item.assetCode]) {
                    if (tradeDetailMap['USC_' + item.assetCode]['newPrice']) {
                        price = tradeDetailMap['USC_' + item.assetCode]['newPrice'];
                    } else {
                        price = 0;
                    }
                    return price;
                }

                // 如 ACT/ETH
                if (tradeDetailMap['ETH_' + item.assetCode]) {
                    if (tradeDetailMap['ETH_' + item.assetCode]['newPrice']) {
                        let ethPrice = tradeDetailMap['ETH_' + item.assetCode]['newPrice'];
                        price = MathTool.multiplication(ethPrice, tradeDetailMap['BTC_ETH']['newPrice']) || 0;
                    } else {
                        price = 0;
                    }
                    return price;
                }

                return price;

                // if (data['BTC_' + item.assetCode]) {
                //     if (coinConfig.symbols['BTC_' + item.symbol] && coinConfig.symbols['BTC_' + item.symbol].online) {
                //         price = data['BTC_' + item.symbol]['newPrice'];
                //     }
                // } else if (item.symbol === 'USDT') {
                //     if (coinConfig.symbols['USDT_BTC'] && coinConfig.symbols['USDT_BTC'].online) {
                //         price = MathTool.division(1, data['USDT_BTC']['newPrice']);
                //     }
                // } else if (item.symbol === 'USC') {
                //     if (coinConfig.symbols['USC_BTC'] && coinConfig.symbols['USC_BTC'].online) {
                //         price = MathTool.division(1, data['USC_BTC']['newPrice']);
                //     }
                // } else if (data['USDT_' + item.symbol]) {
                //     if (coinConfig.symbols['USDT_' + item.symbol] && coinConfig.symbols['USDT_' + item.symbol].online) {
                //         price = MathTool.division(data['USDT_' + item.symbol]['newPrice'], that.btcPrice);
                //     }
                // } else if (data['USC_' + item.symbol]) {
                //     if (coinConfig.symbols['USC_' + item.symbol] && coinConfig.symbols['USC_' + item.symbol].online) {
                //         price = MathTool.division(data['USC_' + item.symbol]['newPrice'], that.btcPrice);
                //     }
                // }
                // if (!price) {
                //     price = 0;
                // }

            }

        },

        _doAssetData(data) {
            let tmpObj;
            let resultMap = {};
            $.map(this.$$assetMap, (outerItem, key) => {
                $.map(data, (item, index) => {
                    if (item.assetCode === outerItem.assetCode) {
                        tmpObj = $.extend({}, {
                            "amountAvailable": '--',
                            "amountLock": '--',
                            'total': 0,
                            'price': 0,
                            'deposit': false,
                            'withdraw': false,
                            'assetCode': item.assetCode,
                            'status': 'DISQUALIFIED'
                        }, item);
                        tmpObj.total = MathTool.add(item.amountAvailable, item.amountLock);
                        resultMap[item.assetCode] = tmpObj;
                    }
                });
            });
            

            this.assets = sorttool.sortByStr(resultMap, 'assetCode');

            this.fetchBTCForkStatus();
            this.getCoinDepositWithdrawList();
        },

        _getTotalValue() {
            let totalBTC = 0;
            let allAssets = this.assets;
            $.map(allAssets, (item, key) => {
                if ($.isNumeric(item.total) === true) {
                    totalBTC = MathTool.add(totalBTC, MathTool.multiplication(item.total, item.price));
                }
            });

            this.totalBTC = filter.floorFix(totalBTC, 8);
            this.totalValue = filter.floorFix(MathTool.multiplication(MathTool.multiplication(totalBTC, this.btcPrice), this.CURRENCY_RMB), 2);

        },


        /**
         * 分页
         * @param pageNo
         */
        changePage(pageNo) {
            this.condition.pageNo = pageNo;
        },

        /**
         * 设置交易密码相关 lanyunlong 2017/12/18
         * */
        setType(coinType, doType, flag) {
            if (flag) {
                this.coinType = coinType;
                if (doType === 'WITHDRAW' && this.isSetPayPassword === false) {
                    this.isShowSetPayPwd = true;
                } else {
                    this.doType = doType;
                    window.location.href = '#/' + doType.toLowerCase() + '/' + coinType;
                }
            }
        },

        fetchPayPsdStatus() {
            commonService.basic().done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    this.isSetPayPassword = rep.data.setPayPassword;
                } else {
                    window.toast(rep.msg);
                }
            })
        },

        hidSetPayPwd() {
            this.isShowSetPayPwd = false;
        },

        onSetPayPwdSuccess() {
            this.isSetPayPassword = true;
            this.doType = 'WITHDRAW';
            window.location.href = '#/withdraw/' + this.coinType;
        },


        fetchBTCForkStatus() {
            this.fetchForkStatusBySymbol('ACT', 'ABTC');//abtc改为act的分叉币
            // this.fetchForkStatusBySymbol('BTC','BCD');
            // this.fetchForkStatusBySymbol('BTC','SBTC');
            // this.fetchForkStatusBySymbol('BTC','BCX');
            // this.fetchForkStatusBySymbol('BTC','LBTC');
            //
            //
            // this.fetchForkStatusBySymbol('BTC','UBTC');
            // this.fetchForkStatusBySymbol('BTC','BTH');
            // this.fetchForkStatusBySymbol('BTC','BTP');
            // this.fetchForkStatusBySymbol('BTC','BTW');
            //
            // this.fetchForkStatusBySymbol('BTC','BTCS');
            // this.fetchForkStatusBySymbol('BTC','BCK');
            // this.fetchForkStatusBySymbol('BTC','LBTC');
            // this.fetchForkStatusBySymbol('BTC','BTF');

        },

        fetchETHForkStatus() {
            // this.fetchForkStatusBySymbol('ETH','EMO');
            // this.fetchForkStatusBySymbol('ETH','ETF');
        },

        fetchLTCForkStatus() {
            // this.fetchForkStatusBySymbol('LTC','LCH');
        },

        /**
         * 查询分叉币种领取状态
         * */
        fetchForkStatusBySymbol(forkAssetCode, targetAssetCode) {
            let param = {
                forkAssetCode,
                targetAssetCode
            };

            service.forkCheck(param).done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    if (targetAssetCode === 'ABTC') {
                        this.assets[targetAssetCode].status = rep.data.candyDtoStatus;
                    }

                    // let cionCode = forkAssetCode+'Forks';
                    // if(targetAssetCode === 'ABTC'){
                    //     this.forkCoins.BTCForks[targetAssetCode].status = rep.data.candyDtoStatus;
                    // }else{
                    //     this.forkCoins[cionCode][targetAssetCode].status = rep.data.candyDtoStatus;
                    // }
                }
            })
        },


        /**
         * 领取糖果
         * */
        getCandy(forkAssetCode, targetAssetCode) {
            let that = this;
            let param = {
                forkAssetCode,
                targetAssetCode
            };

            service.forkReceive(param).done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    window.alert({
                        content: targetAssetCode + that.$t('asset.getSuccess'),
                        btnText: that.$t('common.confirm')
                    });
                    this.getTotalAssets();
                    this.fetchForkStatusBySymbol(forkAssetCode, targetAssetCode);
                } else {
                    window.error(rep.msg);
                }
            })
        },


        /**
         * 展示详细信息
         * */
        forkDetail(coin) {
            this.showForkInfo = true;
            this.forkInfoCoin = coin;
        },

        changeTab(type) {
            this.coinType = '';
            this.keyCoin = '';
            if (type === 'BTC') {
                this.forkType = 'BTC';
                this.fetchBTCForkStatus();
            } else if (type === 'ETH') {
                this.forkType = 'ETH';
                this.fetchETHForkStatus();
            } else if (type === 'LTC') {
                this.forkType = 'LTC';
                this.fetchLTCForkStatus();
            } else {
                this.forkType = '';
            }
            this.tabType = type;
        }
    },

    watch: {}
});